﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using GMS.Model;
using GMS.BLL;
using GMS.Utils;
using Maticsoft.DBUtility;
using System.Text;

public partial class System_Role : System.Web.UI.Page
{
    string sUserId = string.Empty;
    public string CallBackValue;
    string userid;
    List<int> nodevalue = new List<int>();
    protected void Page_Load(object sender, EventArgs e)
    {

        //if (Session["UserID"] == null)
        //{
        //    Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='../../Login.aspx';</script>");
        //    return;
        //};
        if(Session["UserID"] != null)
            userid = Session["UserID"].ToString();

        this.InsertRoleButton.Visible = false;
        this.DelRoleButton.Visible = false;
        this.UpdateModuleRightButton.Visible = false;
        SetAccessRight();
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        DataTable modelDt = null;
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {
            SysFunModuleAccessBLL bll = new SysFunModuleAccessBLL();
            modelDt = bll.GetList("");
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {
            SysFunModuleBLL bll = new SysFunModuleBLL();
            modelDt = bll.GetList("");
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            SysFunModuleOraBLL bll = new SysFunModuleOraBLL();
            modelDt = bll.GetList("");
        }
        else
            return;
        
        LoadModuleTreeView(modelDt, tvModuleRight.Nodes, null);
        GetAllNodeText(tvModuleRight.Nodes); 
        LoadCityTreeView();
        ClientScriptManager script = Page.ClientScript;
        script.RegisterStartupScript(this.GetType(), "", "initChecks()", true);
    }
    void GetAllNodeText(TreeNodeCollection tnc)//判断是否为叶子节点，在叶子节点上加8个字节点
    {
        foreach (TreeNode node in tnc)
        {
            if (node.ChildNodes.Count != 0)
                GetAllNodeText(node.ChildNodes);
            if (node.ChildNodes.Count == 0)
            {
                nodevalue.Add(Convert.ToInt32(node.Value));

                TreeNode[] node1 = new TreeNode[ConstantHelper.C_RIGHT_NUM];
                node1[0] = new TreeNode("查询"); 
                node1[0].Value = "one";
                node1[1] = new TreeNode("新增");
                node1[1].Value = "two";
                node1[2] = new TreeNode("修改");
                node1[2].Value = "three";
                node1[3] = new TreeNode("删除");
                node1[3].Value = "four";
                //node1[4] = new TreeNode("导入");
                //node1[4].Value = "five";
                //node1[5] = new TreeNode("导出");
                //node1[5].Value = "six";
                //node1[6] = new TreeNode("统计");
                //node1[6].Value = "seven";
                //node1[7] = new TreeNode("打印");
                //node1[7].Value = "eight";

                for (int j = 0; j < ConstantHelper.C_RIGHT_NUM; j++)
                {
                    
                   // TreeNode node1 = new TreeNode(btn[j]);
                    node.ChildNodes.Add(node1[j]);
                   
                }
            }
        }
    } 

    
    /// <summary>
    /// 根据选择的角色加载相应的权限
    /// </summary>
    /// <param name="roleid"></param>
    private void SetRoleRight(string roleid,bool IsCityTypeCustom)
    {
        UserRole model = null;       
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {
            UserRoleAccessBLL bll = new UserRoleAccessBLL();
            model = bll.GetSimpleModel(int.Parse(roleid));
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {
            UserRoleBLL bll = new UserRoleBLL();
            model = bll.GetSimpleModel(int.Parse(roleid));
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            UserRoleOraBLL bll = new UserRoleOraBLL();
            model = bll.GetSimpleModel(int.Parse(roleid));
        }
        else
            return;
     

        //if (model.RoleCityRights != null)
        //{
        //    if(!IsCityTypeCustom)
        //        DDLCityRightType.SelectedIndex = DDLCityRightType.Items.IndexOf(DDLCityRightType.Items.FindByValue(model.ROLETYPE.ToString()));
        //    SetCheckedForCityTreeView(model.ROLETYPE, model.RoleCityRights);
        //}
        if (model.RoleModuleIds != null)
        {
            SetCheckedForModuleTreeView(tvModuleRight.Nodes, model.RoleModuleIds);
        }

        ClientScriptManager script = Page.ClientScript;
        script.RegisterStartupScript(this.GetType(), "", "initChecks()", true);
    }

    /// <summary>
    /// 加载模块树
    /// </summary>
    /// <param name="modelDt"></param>
    /// <param name="nodes"></param>
    /// <param name="intParentID"></param>
    private void LoadModuleTreeView(DataTable modelDt, TreeNodeCollection nodes, int? intParentID)
    {
        
        String strExpression = String.Empty;
        if (intParentID == null)
            strExpression = "FATHERMODULEID is null";
        else
            strExpression = "FATHERMODULEID =" + intParentID;
        DataRow[] dr = modelDt.Select(strExpression);
        //for (int j = 0; j < 5; j++)
        //{
        //    if (dr.Length == 0)
        //    {
        //        TreeNode node = new TreeNode(i.ToString());
        //        tn.ChildNodes.Add(node);
        //    }
        //}

        for (int i = 0; i < dr.Length; i++)
        {
            TreeNode tn = new TreeNode();
            tn.Text = dr[i]["MODULENAME"].ToString();
            tn.Value = dr[i]["TABSYSID"].ToString();
            tn.SelectAction = TreeNodeSelectAction.Expand;
            tn.Expanded = false;
            nodes.Add(tn);
            
            //for (int j = 0; j < 5; j++)
            //{
            //    if (Convert.ToInt32(Session["a"]) == 1)
            //    {
            //        TreeNode node = new TreeNode(i.ToString());
            //        tn.ChildNodes.Add(node);
            //    }
            //}
            LoadModuleTreeView(modelDt,tn.ChildNodes, Convert.ToInt32(tn.Value));
        }
        //if (dr.Length == 0)
        //{
        //    Session["a"] = 1;
        //}
        //else
        //    Session["a"] = 0;
    }

    /// <summary>
    /// 加载角色模块权限
    /// </summary>
    /// <param name="modelDt"></param>
    /// <param name="nodes"></param>
    /// <param name="intParentID"></param>
    private void SetCheckedForModuleTreeView(TreeNodeCollection nodes, List<int> moduleRights)
    {
        for (int i = 0; i < nodes.Count; i++)
        {
            TreeNode tn = nodes[i];
            if (tn.Value != "one" && tn.Value != "two" && tn.Value != "three" && tn.Value != "four" && tn.Value != "five" && tn.Value != "six" && tn.Value != "seven" && tn.Value != "eight")
            {
                //tn.Checked = moduleRights.Contains(int.Parse(tn.Value));//这句当可见就有全部权限时有用
                SetCheckedForModuleTreeView(nodes[i].ChildNodes, moduleRights);
            }
            else
            {
                DataSet ds = null;
                if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
                {
                    GMS.BLL.RoleModuleRightAccessBll rmrb = new GMS.BLL.RoleModuleRightAccessBll();
                    string RoleSel = CBLRoles.SelectedValue.ToString();
                    int parentid = Convert.ToInt32(tn.Parent.Value);
                    ds = rmrb.GetList("TABUSERROLECODE in (" + RoleSel + ") and TABSYSID=" + parentid + "");
                }
                else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
                {
                    GMS.BLL.RoleModuleRightAccessBll rmrb = new GMS.BLL.RoleModuleRightAccessBll();
                    string RoleSel = CBLRoles.SelectedValue.ToString();
                    int parentid = Convert.ToInt32(tn.Parent.Value);
                    ds = rmrb.GetList("TABUSERROLECODE in (" + RoleSel + ") and TABSYSID=" + parentid + "");
                }
                else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
                {
                    GMS.BLL.RoleModuleRightOraBLL rmrb = new GMS.BLL.RoleModuleRightOraBLL();
                    string RoleSel = CBLRoles.SelectedValue.ToString();
                    int parentid = Convert.ToInt32(tn.Parent.Value);
                    ds = rmrb.GetList("TABUSERROLECODE in (" + RoleSel + ") and TABSYSID=" + parentid + "");
                }
                else
                    return;
                
                if (ds.Tables[0].Rows.Count == 0)
                {
                    break;
                }
                else
                {
                    string sel = ds.Tables[0].Rows[0]["RIGHTLIST"].ToString();
                    if (sel == null||sel=="")
                    {
                        tn.Checked = false;
                    }
                    StringArrayConverter sac = new StringArrayConverter();
                    object c = sac.ConvertFrom(sel);
                    string[] aa = (string[])c;
                    int[] qq = new int[aa.Length];
                    for (int k = 0; k < aa.Length; k++)
                    {
                        qq[k] = Convert.ToInt32(aa[k]);
                        //Response.Write(qq[i]);
                    }
                    int BtnValue;
                    switch (tn.Value)
                    {
                        case "one":
                            BtnValue = 1;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                        case "two":
                            BtnValue = 2;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                        case "three":
                            BtnValue = 3;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                        case "four":
                            BtnValue = 4;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                        case "five":
                            BtnValue = 5;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                        case "six":
                            BtnValue = 6;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                        case "seven":
                            BtnValue = 7;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                        case "eight":
                            BtnValue = 8;
                            foreach (int j in qq)
                            {
                                if (BtnValue == j)
                                {
                                    tn.Checked = true; break;
                                }
                                else
                                    tn.Checked = false;
                            } break;
                    }
                }
                //if (tn.Value == "one")
                //{
                //    int Btnvalue = 1;
                //    foreach (int j in qq)
                //    {
                //        if (Btnvalue == j)
                //        {
                //            tn.Checked = false; break;
                //        }
                //        else
                //            tn.Checked = true;
                //    }
                //}
         
                //foreach(DataRow dr in ds.Tables[0].Rows)
                //{
                    
                //    string SYSID = dr["TABSYSID"].ToString();
                //    string Btnsel = dr["BtnSel"].ToString();
                //}

                
            }
        }
    }

    /// <summary> 
    /// 加载分公司权限树
    /// </summary>
    private void LoadCityTreeView()
    {
        //#region initial normal city right tree
        //TreeNode tn;
        //tn = new TreeNode("查询", "Select");
        //tn.SelectAction = TreeNodeSelectAction.Expand;
        //TreeNode tnSelect = tn;

        //tn = new TreeNode("增加", "Add");
        //tn.SelectAction = TreeNodeSelectAction.Expand;
        //TreeNode tnAdd = tn;

        //tn = new TreeNode("修改", "Update");
        //tn.SelectAction = TreeNodeSelectAction.Expand;
        //TreeNode tnUpdate = tn;

        //tn = new TreeNode("删除", "Delete");
        //tn.SelectAction = TreeNodeSelectAction.Expand;
        //TreeNode tnDelete = tn;

        //List<GMS.Model.CitySeq> cs = (List<GMS.Model.CitySeq>)Application["CityList"];

        //for (int i = 0; i < cs.Count; i++)
        //{
        //    tnDelete.ChildNodes.Add(new TreeNode(cs[i].cityname, cs[i].citycode));
        //    tnSelect.ChildNodes.Add(new TreeNode(cs[i].cityname, cs[i].citycode));
        //    tnAdd.ChildNodes.Add(new TreeNode(cs[i].cityname, cs[i].citycode));
        //    tnUpdate.ChildNodes.Add(new TreeNode(cs[i].cityname, cs[i].citycode));
        //}

        //this.tvCityRight.Nodes.Add(tnSelect);
        //this.tvCityRight.Nodes.Add(tnAdd);
        //this.tvCityRight.Nodes.Add(tnUpdate);
        //this.tvCityRight.Nodes.Add(tnDelete);
        ////tvCityRight.CollapseAll();

        //#endregion end initial  normal city right tree;

        //#region initial special city right
        //CBLOperation.Items.Add(new ListItem("查询", "Select"));
        //CBLOperation.Items.Add(new ListItem("增加", "Add"));
        //CBLOperation.Items.Add(new ListItem("修改", "Update"));
        //CBLOperation.Items.Add(new ListItem("删除", "Delete"));
        //#endregion end initial special city right
    }

    /// <summary>
    /// 加载角色分公司权限
    /// </summary>
    private void SetCheckedForCityTreeView(int roleType,Dictionary<int, List<string>> cityRights)
    {
        if (cityRights == null)
            return;
        bool SpecRight = (roleType == (int)GMS.Utils.EnumHelper.E_YesOrNo.YES);
        //if is special right and has city rights,set only operate's checked is true
        if (SpecRight)
        {
            CBLOperation.Items[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.SEARCH].Selected= cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.SEARCH);
            CBLOperation.Items[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.INSERT].Selected= cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.INSERT);
            CBLOperation.Items[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.UPDATE].Selected= cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.UPDATE);
            CBLOperation.Items[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.DELETE].Selected= cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.DELETE);
            return;
        }

        //if is normal right set type,set the city checked is true

        List<string> searchCitys = new List<string>();
        List<string> insertCitys = new List<string>();
        List<string> updateCitys = new List<string>();
        List<string> deleteCitys = new List<string>();
        //if has city rights
        if (cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.SEARCH))
        {
            searchCitys = cityRights[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.SEARCH];
        }
        if (cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.INSERT))
        {
            insertCitys = cityRights[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.INSERT];
        }
        if (cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.UPDATE))
        {
            updateCitys = cityRights[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.UPDATE];
        }
        if (cityRights.ContainsKey((int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.DELETE))
        {
            deleteCitys = cityRights[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.DELETE];
        }

        foreach (TreeNode tn in tvCityRight.Nodes[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.SEARCH].ChildNodes)
        {
            tn.Checked = searchCitys.Contains(tn.Value);
        }
        foreach (TreeNode tn in tvCityRight.Nodes[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.INSERT].ChildNodes)
        {
            tn.Checked = insertCitys.Contains(tn.Value);
        }
        foreach (TreeNode tn in tvCityRight.Nodes[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.UPDATE].ChildNodes)
        {
            tn.Checked = updateCitys.Contains(tn.Value);
        }
        foreach (TreeNode tn in tvCityRight.Nodes[(int)GMS.Utils.EnumHelper.E_RoleCityOperateIndex.DELETE].ChildNodes)
        {
            tn.Checked = deleteCitys.Contains(tn.Value);
        }
        //tvCityRight.ExpandAll();
        
    }

    protected void CBLRoles_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        //鼠标变成沙漏等待
        Page.RegisterStartupScript("wait", " <script> document.body.style.cursor   =   'wait '; </script> ");
        ChangeRole(false);
    }

    private void ChangeRole(bool IsCityTypeCustom)
    {
        string sltRoles = "";
        //bool addRight = true;
        //string sltRoleTypes = "";
        foreach (ListItem item in CBLRoles.Items)
        {
            if (item.Selected)
            {
                sltRoles += item.Value.Split('-')[0] + ",";
                //sltRoleTypes += item.Value.Split('-')[1];
            }
        }
        //if (sltRoleTypes.Contains("0") && sltRoleTypes.Contains("1"))
        //{
        //    AddCityRightButton.Enabled = false;
        //    DelCityRightButton.Enabled = false;
        //    DDLCityRightType.Enabled = false;
        //}
        //else
        //{
        //    AddCityRightButton.Enabled = true;
        //    DelCityRightButton.Enabled = true;
        //    DDLCityRightType.Enabled = true;
        //}
        if (sltRoles == "")
        {
            RemoveAllChecked();
            return;
        }
        //choose single,set its rights
        sltRoles = sltRoles.TrimEnd(',');
        if(!sltRoles.Contains(","))
        {
            SetRoleRight(sltRoles, IsCityTypeCustom);
            return;
        }
        //clear rights or reload trees
        RemoveAllChecked();
    }

    private void RemoveAllChecked()
    {
        for (int i = 0; i < CBLOperation.Items.Count;i++ )
            CBLOperation.Items[i].Selected = false;
        TreeNodeCollection checkedNodes = tvCityRight.CheckedNodes;
        int nodeCount = checkedNodes.Count;
        for (int i = 0; i < nodeCount; i++)
        {
            checkedNodes[i].Checked = false;
            nodeCount--;
            i--;
        }
        checkedNodes = tvModuleRight.CheckedNodes;
        nodeCount = checkedNodes.Count;
        for (int i = 0; i < nodeCount; i++)
        {
            checkedNodes[i].Checked = false;
            nodeCount--;
            i--;
        }
    }

    public void SetCityTreeTrue(TreeNode tn, string sCityCode) 
    {
        for (int i = 0; i < tn.ChildNodes.Count; ++i)
        {
            if (tn.ChildNodes[i].Value.Equals(sCityCode))
            {
                tn.ChildNodes[i].Checked = true;
                break;
            }
        }
    }

    /// <summary>
    /// 提交、增加或去除模块权限
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void UpdateModuleRight_Click(object sender, EventArgs e)
    {

        Button btn = sender as Button;
        TreeNodeCollection nodes = tvModuleRight.CheckedNodes;
        List<string> roleids = new List<string>();
        foreach (ListItem i in CBLRoles.Items)
        {
            if (i.Selected)
                roleids.Add(i.Value.Split('-')[0]);
        }
        if (roleids.Count == 0)
        {
            Alert("至少选择一个角色!");
            return;
        }
        List<RoleModuleRightModel> newRoleModuleRgihts = new List<RoleModuleRightModel>();
        RoleModuleRightModel module;
        foreach (TreeNode node in nodes)
        {
            if (node.Value != "one" && node.Value != "two" && node.Value != "three" && node.Value != "four" && node.Value != "five" && node.Value != "six" && node.Value != "seven" && node.Value != "eight")
            {
                module = new RoleModuleRightModel();
                module.TABSYSID = int.Parse(node.Value);
                module.CREATOR = userid;
                newRoleModuleRgihts.Add(module);
            }
            //else
            //{
            // string pa=node.Parent.Value;
            // if (node.Checked == false)
            // {
            //     GMS.BLL.RoleModuleRightAccessBll rmrb = new GMS.BLL.RoleModuleRightAccessBll();
            //     string RoleSel = CBLRoles.SelectedValue.ToString();
            //     int parentid = Convert.ToInt32(pa);
            //     DataSet ds = rmrb.GetList("TABUSERROLECODE in (" + RoleSel + ") and TABSYSID=" + parentid + "");
            //     string sel = ds.Tables[0].Rows[0]["BtnSel"].ToString();
            //     StringBuilder str = new StringBuilder();
            //     str.Append(sel);
            //     str.Append(",");
            //     str.Append(node.Value);
            //     rmrb.UpdateBtn(str.ToString(), parentid, Convert.ToInt32(RoleSel));
                 
            // }

            //}
            

        }
       // TreeNodeCollection tnc = tvModuleRight.Nodes;
        Dictionary<int, RoleModuleRightModel> roleModelDict = new Dictionary<int, RoleModuleRightModel>();
        UpdateNode(tvModuleRight.Nodes, ref roleModelDict); 
        //foreach (TreeNode n in tnc)
        //{
            //if (n.ChildNodes.Count != 0)
            //if (n.Value != "one" && n.Value != "two" && n.Value != "three" && n.Value != "four" && n.Value != "five" && n.Value != "six" && n.Value != "seven" && n.Value != "eight")
            //{

            //}
            //else
            //{
            //    string pa = n.Parent.Value;
            //    if (n.Checked == false)
            //    {
            //        GMS.BLL.RoleModuleRightAccessBll rmrb = new GMS.BLL.RoleModuleRightAccessBll();
            //        string RoleSel = CBLRoles.SelectedValue.ToString();
            //        int parentid = Convert.ToInt32(pa);
            //        DataSet ds = rmrb.GetList("TABUSERROLECODE in (" + RoleSel + ") and TABSYSID=" + parentid + "");
            //        string sel = ds.Tables[0].Rows[0]["BtnSel"].ToString();
            //        StringBuilder str = new StringBuilder();
            //        str.Append(sel);
            //        str.Append(",");
            //        str.Append(n.Value);
            //        rmrb.UpdateBtn(str.ToString(), parentid, Convert.ToInt32(RoleSel));

            //    }
            //}
        //}


        try
        {
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                RoleModuleRightAccessBll bll = new RoleModuleRightAccessBll();
                bll.UpdateRoleModuleRight(roleids, roleModelDict, Convert.ToInt32(btn.CommandName));
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                UserRoleBLL bll = new UserRoleBLL();
                bll.UpdateRoleModuleRight(roleids, newRoleModuleRgihts, Convert.ToInt32(btn.CommandName));
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                RoleModuleRightOraBLL bll = new RoleModuleRightOraBLL();
                bll.UpdateRoleModuleRight(roleids, roleModelDict, Convert.ToInt32(btn.CommandName));
            }
            else
                return;

            //if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            //{
            //    UserRoleAccessBLL bll = new UserRoleAccessBLL();
            //    bll.UpdateRoleModuleRight(roleids, newRoleModuleRgihts, Convert.ToInt32(btn.CommandName));
            //}
            //else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            //{
            //    UserRoleBLL bll = new UserRoleBLL();
            //    bll.UpdateRoleModuleRight(roleids, newRoleModuleRgihts, Convert.ToInt32(btn.CommandName));
            //}
            //else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            //{
            //    UserRoleOraBLL bll = new UserRoleOraBLL();
            //    bll.UpdateRoleModuleRight(roleids, newRoleModuleRgihts, Convert.ToInt32(btn.CommandName));
            //}
            //else
            //    return;

            
            this.Page.RegisterStartupScript("onload", "<script>alert('角色模块权限更新成功！');</script>");
            
            //因为改了权限，所以需要清空全局变量（存权限），以便下次访问的时候重新从数据库加载
            GMS.Web.AppOperation.ApplicationOperation.SetRoleModuleRight(null);
            GMS.Web.AppOperation.ApplicationOperation.SetUserModuleList(1,null);
        }
        catch (ArgumentException ae)
        {
            //为什么下句出不来？
            this.Page.RegisterStartupScript("onload", "<script>alert('角色模块权限更新失败！" + ae.Message+"');</script>");
            Tip.Text = "角色模块权限更新失败！" + ae.Message;
        }
        catch (Exception ex)
        {
            //为什么下句出不来？
            this.Page.RegisterStartupScript("onload", "<script>alert('角色模块权限更新失败！" + ex.Message + "');</script>");
            
            Tip.Text = "角色模块权限更新失败！" + ex.Message;
        }

    }

    private bool NodeCheckedOrIndeterminate(TreeNodeCollection tnc)
    {
        foreach (TreeNode node in tnc)
        {
            if (node.Checked)
                return true;//子节点中，只要有一个（不管是真正节点还是权限节点）打勾了，那么这个节点就是Checked或者Indeterminate
            if (node.ChildNodes.Count != 0)//有子节点
                return NodeCheckedOrIndeterminate(node.ChildNodes);
        }
        return false;
    }

    private void UpdateNode(TreeNodeCollection tnc, ref Dictionary<int, RoleModuleRightModel> roleModelDict)
    {
        foreach (TreeNode n in tnc)
        {
            if (n.ChildNodes.Count != 0)//有子节点
                UpdateNode(n.ChildNodes, ref roleModelDict);

            if (n.Value != "one" && n.Value != "two" && n.Value != "three" && n.Value != "four" && n.Value != "five" && n.Value != "six" && n.Value != "seven" && n.Value != "eight")
            {//表示非叶子节点，即非权限节点（非one，two，three，four），可能是实际的叶子节点，也可能是实际的非叶子节点
                bool addSearchRight = false;//如何判断部分选中？用js？如何做？
                if (n.Checked == true)
                    addSearchRight = true;
                else
                {
                    if (NodeCheckedOrIndeterminate(n.ChildNodes))
                        addSearchRight = true;
                }

                if (addSearchRight == true)
                {
                    int id = Convert.ToInt32(n.Value);
                    if (!roleModelDict.ContainsKey(id))
                    {
                        RoleModuleRightModel newmodel = new RoleModuleRightModel();
                        newmodel.TABSYSID = id;
                        newmodel.TABUSERROLECODE = int.Parse(CBLRoles.SelectedValue);
                        roleModelDict.Add(id, newmodel);
                    }

                    //此处判断应该去掉实际有意义的叶子节点（就是只要判断一下非叶子节点），如果判断呢？根据实际叶子节点的叶子节点的值？（one，。。。）
                    if (string.IsNullOrEmpty(roleModelDict[id].RIGHTLIST))
                        roleModelDict[id].RIGHTLIST = roleModelDict[id].RIGHTLIST + "1";
                    else
                    {
                        if(roleModelDict[id].RIGHTLIST.IndexOf("1") == -1)//表示没有出现1这个权限
                            roleModelDict[id].RIGHTLIST = roleModelDict[id].RIGHTLIST + "," + "1";
                    }
                }

            }
            else
            {
                switch (n.Value)
                {
                    case "one":
                        n.Value = "1";break;
                    case "two":
                        n.Value = "2";break;
                    case "three":
                        n.Value = "3";break;
                    case "four":
                        n.Value = "4"; break;
                    //case "five":
                    //    n.Value = "5"; break;
                    //case "six":
                    //    n.Value = "6"; break;
                    //case "seven":
                    //    n.Value = "7"; break;
                    //case "eight":
                    //    n.Value = "8"; break;
                    default:
                        n.Value = "1"; break;//？？？
                }

                //把权限（1,或2,3,4）加到父节点上去
                string pa = n.Parent.Value;
                int parentid = Convert.ToInt32(pa);
                if (!roleModelDict.ContainsKey(parentid))
                {
                    RoleModuleRightModel newmodel = new RoleModuleRightModel();
                    newmodel.TABSYSID = parentid;
                    newmodel.TABUSERROLECODE = int.Parse(CBLRoles.SelectedValue);
                    roleModelDict.Add(parentid, newmodel);
                }
                if (n.Checked == true)
                {
                    if(string.IsNullOrEmpty(roleModelDict[parentid].RIGHTLIST))
                        roleModelDict[parentid].RIGHTLIST = roleModelDict[parentid].RIGHTLIST + n.Value;
                    else
                        roleModelDict[parentid].RIGHTLIST = roleModelDict[parentid].RIGHTLIST + "," + n.Value;
                  

                }
                //string pa = n.Parent.Value;
                //if (n.Checked == false)
                //{
                //    GMS.BLL.RoleModuleRightAccessBll rmrb = new GMS.BLL.RoleModuleRightAccessBll();
                //    string RoleSel = CBLRoles.SelectedValue.ToString();
                //    int parentid = Convert.ToInt32(pa);
                //    DataSet ds = rmrb.GetList("TABUSERROLECODE in (" + RoleSel + ") and TABSYSID=" + parentid + "");
                //    string sel = ds.Tables[0].Rows[0]["BtnSel"].ToString();
                //    StringBuilder str = new StringBuilder();
                //    str.Append(sel);
                //    str.Append(",");
                //    str.Append(n.Value);
                //    rmrb.UpdateBtn(str.ToString(), parentid, Convert.ToInt32(RoleSel));

                //}
            }
          //  Response.Write(node.Text + " ");
        }
    } 

    ///// <summary>
    ///// 提交、增加或去除分公司权限
    ///// </summary>
    ///// <param name="sender"></param>
    ///// <param name="e"></param>
    //protected void UpdateCityRight_Click(object sender, EventArgs e)
    //{
    //    Button btn = sender as Button;
    //    UserRoleBLL bll = new UserRoleBLL();
    //    List<string> roleids = new List<string>();
    //    foreach (ListItem i in CBLRoles.Items)
    //    {
    //        if (i.Selected)
    //            roleids.Add(i.Value.Split('-')[0]);
    //    }
    //    if (roleids.Count == 0)
    //    {
    //        Alert("至少选择一个角色!");
    //        return;
    //    }
    //    bool SpecRight = (DDLCityRightType.SelectedIndex == (int)EnumHelper.E_YesOrNo.YES);

    //    if (SpecRight)
    //    {
    //        //<opeaate,1or0>
    //        Dictionary<string, int> newCityRights = new Dictionary<string, int>();//search,1
    //        foreach(ListItem item in CBLOperation.Items)
    //        {
    //            if (item.Selected)
    //                newCityRights.Add(item.Value, 1);
    //            else
    //                newCityRights.Add(item.Value, 0);
    //        }

    //        try
    //        {
    //            bll.UpdateRoleCitySpecRight(roleids,userid, newCityRights, Convert.ToInt32(btn.CommandName));
    //            Tip.Text = "角色分公司权限更新成功";
    //        }
    //        catch (ArgumentException ae)
    //        {
    //            Tip.Text = "角色分公司权限更新失败！" + ae.Message;
    //        }
    //        catch (Exception ex)
    //        {
    //            Tip.Text = "角色分公司权限更新失败！" + ex.Message;
    //        }
    //    }
    //    else
    //    {
    //        //<city,<operate>>
    //        Dictionary<string, List<string>> newCityRights = new Dictionary<string, List<string>>();

    //        foreach(TreeNode node in tvCityRight.CheckedNodes)
    //        {
    //            if (node.Depth == 0)
    //                continue;

    //            if (!newCityRights.ContainsKey(node.Value))
    //            {
    //                newCityRights.Add(node.Value, new List<string>());
    //            }
    //           newCityRights[node.Value].Add(node.Parent.Value);
    //       }
    //       try
    //       {
    //           bll.UpdateRoleCityNonSpecRight(roleids, userid, newCityRights, Convert.ToInt32(btn.CommandName));
    //           Tip.Text = "角色分公司权限更新成功";
    //       }
    //       catch (ArgumentException ae)
    //       {
    //           Tip.Text = "角色分公司权限更新失败！" + ae.Message;
    //       }
    //       catch (Exception ex)
    //       {
    //           Tip.Text = "角色分公司权限更新失败！" + ex.Message;
    //       }
    //    }
    //}

    /// <summary>
    /// 新建角色
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button_Insert_Click(object sender, EventArgs e)
    {       
        string roleid = Request.Form["hidRoleId"];
        try
        {

            if (string.IsNullOrEmpty(roleid))
            {
                if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
                {
                    UserRoleAccessBLL bll = new UserRoleAccessBLL();
                    bll.Add(userid, Request.Form["newRoleName"].Trim());
                }
                else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
                {
                    UserRoleBLL bll = new UserRoleBLL();
                    bll.Add(userid, Request.Form["newRoleName"].Trim());
                }
                else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
                {
                    UserRoleOraBLL bll = new UserRoleOraBLL();
                    bll.Add(userid, Request.Form["newRoleName"].Trim());
                }
                else
                    return;

                this.Page.RegisterStartupScript("onload", "<script>alert('角色创建成功，请为角色配置权限！');</script>");
                //Tip.Text = "角色创建成功，请为角色配置权限！";
            }
            else
            {
                if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
                {
                    UserRoleAccessBLL bll = new UserRoleAccessBLL();
                    bll.Update(userid, int.Parse(roleid), Request.Form["newRoleName"].Trim());
                }
                else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
                {
                    UserRoleBLL bll = new UserRoleBLL();
                    bll.Update(userid, int.Parse(roleid), Request.Form["newRoleName"].Trim());
                }
                else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
                {
                    UserRoleOraBLL bll = new UserRoleOraBLL();
                    bll.Update(userid, int.Parse(roleid), Request.Form["newRoleName"].Trim());
                }
                else
                    return;
                this.Page.RegisterStartupScript("onload", "<script>alert('角色名称修改成功！');</script>");
                //Tip.Text = "角色名称修改成功！";
            }
            CBLRoles.DataBind();
        }
        catch (ArgumentException ae)
        {
            Tip.Text = "保存失败！" + ae.Message;
        }
        catch (Exception ex)
        {
            Tip.Text = "保存失败！" + ex.Message;
        }
    }

    /// <summary>
    /// 删除角色
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DelRoleButton_Click(object sender, EventArgs e)
    {        
        string roleids = "";
        foreach (ListItem i in CBLRoles.Items)
        {
            if (i.Selected)
                roleids += "'"+i.Value.Split('-')[0]+"',";
        }
        try
        {
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                UserRoleAccessBLL bll = new UserRoleAccessBLL();
                bll.DeleteMulti(roleids.TrimEnd(','), userid);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                UserRoleBLL bll = new UserRoleBLL();
                bll.DeleteMulti(roleids.TrimEnd(','), userid);
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                UserRoleOraBLL bll = new UserRoleOraBLL();
                bll.DeleteMulti(roleids.TrimEnd(','), userid);
            }
            else
                return;

            this.Page.RegisterStartupScript("onload", "<script>alert('角色删除成功！');</script>");
            //Tip.Text = "角色删除成功！";
            CBLRoles.DataBind();
        }
        catch (ArgumentException ae)
        {
            Tip.Text = "角色删除失败！" + ae.Message;
        }
        catch (Exception ex)
        {
            Tip.Text = "角色删除失败！" + ex.Message;
        }
    }
    private void Alert(string msg)
    {
        ClientScriptManager script = Page.ClientScript;
        script.RegisterStartupScript(this.GetType(), "", "alert('" + msg.Replace('\'', ' ').Replace("\r\n", "") + "');", true);
    }

    private void DoRight(GMS.Model.User user, int TabSysID)
    {
        int[] right = RoleModuleRightOper.GetRoleModuleRightInt(user, TabSysID);

        foreach (int i in right)
        {
            switch (i)
            {
                case (int)EnumHelper.E_Right.R_SEARCH:
                    //BtnCustomSearch.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_INSERT:
                    this.InsertRoleButton.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_UPDATE:
                    this.UpdateModuleRightButton.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_DELETE:
                    this.DelRoleButton.Visible = true;
                    break;
                default:
                    break;
            }
        }
    }

    private void SetAccessRight()
    {
        GMS.Model.User user = (GMS.Model.User)Session["_User"];
        if (user == null)
        {
            Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='" + Request.ApplicationPath + "/Login.aspx';</script>");
            return;
        }

        int TabSysID; //模块ID
        if (Request.Params["TabSysID"] != null)
        {
            TabSysID = Int32.Parse(Request.Params["TabSysID"]);
            if (Session["TabSysID"] == null)
            {
                Session.Add("TabSysID", TabSysID);
            }
            else
            {
                Session["TabSysID"] = TabSysID;
            }

            DoRight(user, TabSysID);
        }
        else if (Session["TabSysID"] != null)
        {
            DoRight(user, Int32.Parse(Session["TabSysID"].ToString()));
        }
        else
        {
            this.InsertRoleButton.Visible = true;
            this.DelRoleButton.Visible = true;
            this.UpdateModuleRightButton.Visible = true;
        }

    }
}
